-- FUNCTION: public.widget_BarChart_Pharmacy_LowSellingProducts(date, text, integer)

-- DROP FUNCTION public."widget_BarChart_Pharmacy_LowSellingProducts"(date, text, integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_Pharmacy_LowSellingProducts"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;

begin
create  Temp TABLE temp_table 
( ddate date, 
  dname text,
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";

raise notice 'filtervalue %', filtervalue;

--fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;

for f in SELECT generate_series("fromDate"-filtervalue, "fromDate"+filtervalue,  intervaldata) weeks
    loop 
	raise notice 'fromdate %', "fromDate"-filtervalue;
	raise notice 'todate %', "fromDate"+filtervalue;
	insert into temp_table (ddate,dname,countdata)
--------------------------------------------------

with lowSellingData as(
select psd."PharmacyProductId",PP."ProductName",  count(psd."PharmacyProductId") "Count" 
from "PharmacySaleDetail" psd
	
	join "PharmacyProduct" pp on pp."PharmacyProductId" = psd."PharmacyProductId"	
	join "PharmacySaleHeader" psh on psh."PharmacySaleHeaderId" = psd."PharmacySaleHeaderId"
	where   psh."CreatedDate"::date >= f.weeks::text::date and psh."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date  
	group by psd."PharmacyProductId" ,PP."ProductName" 
	

)
select f.weeks, lsd."ProductName", lsd."Count"
from lowSellingData lsd
order by "Count" asc 
	limit "displayCount";

----------

		
end loop;
	RETURN QUERY
	
	select A.ddate,A.dname,A.countdata from temp_table A
	order by A.countData asc
	limit "displayCount";
	drop table temp_table;
	--drop table temp_date_table;				
	
END;
$BODY$;

ALTER FUNCTION public."widget_BarChart_Pharmacy_LowSellingProducts"(date, text, integer)
    OWNER TO postgres;
